package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentDto;
import com.heima.comment.dto.CommentLikeDto;
import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApCommentLike;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;

import com.heima.common.util.UserThreadLocalUtil;
import com.heima.vo.ApCommentVo;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl implements ICommentService {

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        // 判断内容是否大于140字
        if (dto == null || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 判断用户是否登录(要求使用手机号和密码登录的用户)
        User user = UserThreadLocalUtil.get();
        if (user == null&&user.getUserId() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 安全过滤--阿里云文本审核  todo 自行实现
        ApComment comment = new ApComment();
        comment.setUserId(user.getUserId());
        // 根据用户id查询用户,调用用户微服务提供的远程接口
        ResponseResult<ApUser> userResponseResult = userFeign.getUserById(user.getUserId());
        if (userResponseResult.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUser apUser = userResponseResult.getData();
            comment.setUserName(apUser.getName());
            comment.setImage(apUser.getImage());
        }
        comment.setArticleId(dto.getArticleId());
        comment.setContent(dto.getContent());
        comment.setLikes(0); //这个评论收到的点赞数
        comment.setRepay(0); //这个评论收到的回复数
        comment.setCreatedTime(new Date());
        // MongoDB保存评论
        mongoTemplate.save(comment);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult load(CommentDto dto) {
        // 根据文章id查询评论列表
        // 按照创建时间倒序排列
        // 分页判断数据小于前端传递的最小时间
        // 每页默认显示10条评论数据
        if (dto.getSize() == null || dto.getSize() <= 0 || dto.getSize() >= 50) {
            dto.setSize(10);
        }
        Query query = new Query(Criteria.where("articleId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));

        // 分页 和 排序
        Pageable page = PageRequest.of(1, dto.getSize(), Sort.Direction.DESC, "createdTime");
        query.with(Sort.by(Sort.Direction.DESC,"createTime"));
        query.limit(dto.getSize());

        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        log.info(apComments.toString());

        // TODO 登录用户需要查看当前返回的列表中是否已经有点赞记录

        User user = UserThreadLocalUtil.get();
        if(user != null && user.getUserId() != 0){
            List<ApCommentVo> comVoList = new ArrayList<>();
            for(ApComment comment :apComments){
                ApCommentVo apCommentVo = new ApCommentVo();
//                BeanUtils.copyProperties(comment,apCommentVo);
                BeanUtils.copyProperties(comment,apCommentVo);
                //这里用到了redis的k-v数据结构 根据用户id commentid拼接出key 去redis里查 查到就在vo类中标记已点赞
                Boolean hasKey = redisTemplate.hasKey("comment_like_"+user.getUserId()+"_"+comment.getId());
                apCommentVo.setOperation(hasKey?0:1);
                comVoList.add(apCommentVo);
            }
            return ResponseResult.okResult(comVoList);
        }
        return ResponseResult.okResult(apComments);
    }


    @Override
    public ResponseResult like(CommentLikeDto dto) {
        // 获取当前的用户
        User user = UserThreadLocalUtil.get();
        if (user == null||user.getUserId()==0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建点赞记录
        ApCommentLike like = new ApCommentLike();
        like.setUserId(user.getUserId());
        like.setCommentId(dto.getCommentId());
        like.setOperation(dto.getOperation());

        // 保存点赞或取消点赞记录
        mongoTemplate.save(like);

        // 更新评论表的点赞数量+1或者-1
        Query commentQuery = new Query();
        commentQuery.addCriteria(Criteria.where("_id").is(dto.getCommentId()));
        Update update = new Update();
        if (dto.getOperation() == 1) {
            update.inc("likes",-1);
            //取消点赞就在redis里删除key
            redisTemplate.delete("comment_like_"+user.getUserId()+"_"+dto.getCommentId());
        }else{
            update.inc("likes",1);
            //点赞就在redis里构建key
            redisTemplate.boundValueOps("comment_like_"+user.getUserId()+"_"+dto.getCommentId()).set("");

        }
        mongoTemplate.updateFirst(commentQuery, update, ApComment.class);
        log.info("这是点赞功能");
        return ResponseResult.okResult();
    }

}
